package org.itboys.manager;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.entity.SysDictionary;
import org.itboys.admin.service.SysDictionaryService;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.fuzion.constant.FuzionConstants;
import org.itboys.fuzion.dto.FuzionMemberRedisDto;
import org.itboys.fuzion.entity.FuzionMember;
import org.itboys.fuzion.entity.IncomeExpenditureRecords;
import org.itboys.fuzion.entity.ScoreLevel;
import org.itboys.fuzion.kuaiqian.KQResult;
import org.itboys.fuzion.kuaiqian.KQService;
import org.itboys.fuzion.mysql.dao.FuziongMemberStatisticsMapper;
import org.itboys.fuzion.mysql.orm.FuziongMemberStatistics;
import org.itboys.fuzion.mysql.orm.PublicRow;
import org.itboys.fuzion.mysql.orm.PublicRowRecord;
import org.itboys.fuzion.mysql.service.FuziongMemberStatisticsService;
import org.itboys.fuzion.mysql.service.PublicRowRecordService;
import org.itboys.fuzion.mysql.service.PublicRowService;
import org.itboys.fuzion.service.FuzionMemberService;
import org.itboys.fuzion.service.IncomeExpenditureRecordsService;
import org.itboys.fuzion.service.ScoreLevelService;
import org.itboys.pay.alipay.AlipayWapResult;
import org.itboys.pay.constant.PayConstants;
import org.itboys.pay.weixin.WXPayService;
import org.itboys.product.cache.OrderLoader;
import org.itboys.product.constant.ProductConstant;
import org.itboys.product.dto.OrderDto;
import org.itboys.product.entity.Order;
import org.itboys.product.service.OrderService;
import org.itboys.redis.RedisCacheClient;
import org.itboys.tools.WeixinSendInfoThread;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.entity.WeixinSendInfo;
import org.itboys.weixin.service.WeixinConfigService;
import org.itboys.weixin.service.WeixinSendInfoService;
import org.itboys.weixin.tools.WeixinSendUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;

@Service
public class OrderMemberService {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Resource(name="orderLoader")
	private OrderLoader orderLoader;

    @Autowired
    private WeixinConfigService weixinConfigService;
    @Autowired
    private FuzionMemberService memberService;
    @Autowired
    private FuziongMemberStatisticsMapper fuziongMemberStatisticsMapper;
    @Autowired
    private IncomeExpenditureRecordsService incomeExpenditureRecordsService;
    @Autowired
    private PublicRowService publicRowService;
    @Autowired
    private OrderService orderService;
	@Autowired
	private RedisCacheClient redisCacheClient;
	@Autowired
	private FuziongMemberStatisticsService fuziongMemberStatisticsService;
	@Autowired
	private PublicRowRecordService publicRowRecordService;
	@Autowired
	private SysDictionaryService sysDictionaryService;
	@Autowired
	private WeixinSendInfoService weixinSendInfoService;
	@Autowired
	private ScoreLevelService scoreLevelService;
	@Autowired
	private ResourceHolder resourceHolder;
	
	private static final String FUZION_PUBLIC_ROW_KEY = "FUZION_PUBLIC_ROW_KEY";//公排时 将要弹出的缓存key前缀
	private static final String FUZION_PUBLIC_ROW_DTO = "fuzion_public_row_dto_";//缓存公排对象KEY的前缀
	private static final String FUZION_PUBLIC_ROW_PUSHID_NUM = "fuzion_public_row_pushid_num_";//缓存公排中需要push的数据统计

	private static final String QK_NOTIFY_FAIL = "<result>2</result><redirecturl></redirecturl>";
	private static final String QK_NOTIFY_SUCCESS = "<result>1</result><redirecturl>{url}</redirecturl>";

	/**
	 * 微信支付异步回调处理
	 *
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public String weixinNotify1(String orderNo) throws Exception{
		IncomeExpenditureRecords records = null;//会员交易记录
		IncomeExpenditureRecords sellRecords = null;//店铺交易记录
		FuzionMember member = null;
		boolean readed = true;
		try {
			Order order = orderService.getByField("orderNo", orderNo);
			logger.info("**********orderNo**********"+orderNo);
			if(order == null){
				logger.info("****************order == null*************");
				return CommonConstants.FAIL;
			}
			logger.info("*******order************"+order.toString());
			member = memberService.getById(order.getMemberId());
			if(member.getReaded()){
				readed = false;
			}
			member.setReaded(true);
			//WeixinConfig weixinConfig = weixinConfigService.getById(Long.valueOf(member.getWeixinId()));
            /*if(wapResult.getPrice().compareTo(new BigDecimal(order.getTotalFee())) != 0){//支付金额不正确
                logger.info("****************price error*************");
                return CommonConstants.FAIL;
            }*/
			//修改订单状态并生成支付记录
			//   能量豆支付的处理
			FuziongMemberStatistics statistics = fuziongMemberStatisticsMapper.getByMemberId(member.getId());
//        statistics.setBuyCount(statistics.getBuyCount() + 1);

			if(order.getProductId().equals(ProductConstant.EnergyBeanProduct.BEAN_PRODUCT_ID)){//如果购买的是能量豆,能量豆购买数量加一
				statistics.setEnergyBean(statistics.getEnergyBean() + 1);
				statistics.setNowEnergyBean(statistics.getNowEnergyBean() + 1);
				//判断等级  这里应该是购买的能量豆总数加上推荐的会员数
				//long recCount = memberService.countMemberByRecId(member.getRecId());
                /*ScoreLevel scoreLevel = scoreLevelService.getByScore(statistics.getEnergyBean() - 1);
                if(scoreLevel != null && statistics.getScoreId() < scoreLevel.getId()){
                	scoreName = scoreLevel.getLevelName();
                	statistics.setScoreId(scoreLevel.getId());//设置会员等级
                }else if(scoreLevel == null && statistics.getEnergyBean() == 1){//会员只购买了一个能量豆
                	if(statistics.getScoreId() == 0){//还没有会员等级时  设置为青铜   如果有其他会员等级  不作处理
                		statistics.setScoreId(1L);//设置会员等级
                		scoreName = "青铜";
                	}
                }*/

				//公排逻辑
				//buyThanPublicRow(member.getId());
			}
			//购买商品 处理推荐人收益
			orderService.recIncome(member, order.getProductId());
			fuziongMemberStatisticsMapper.update(statistics);//扣除能量豆

			//生成收支明细表
			records = new IncomeExpenditureRecords();
			records.setMemberId(member.getId());
			records.setType(FuzionConstants.TYPE_ONE);
			records.setMoney(0 - order.getTotalFee());
			if(order.getProductId().equals(ProductConstant.EnergyBeanProduct.BEAN_PRODUCT_ID)){
				records.setObjType(FuzionConstants.IncomeExpenditure.BEAN_SHOPPING);
			} else {
				records.setObjType(FuzionConstants.IncomeExpenditure.SHOPPING_MONEY);
			}
			records.setObjId(String.valueOf(order.getId()));
			incomeExpenditureRecordsService.insert(records);
			// 卖家账户余额变动
			FuziongMemberStatistics sellerStatistics = fuziongMemberStatisticsMapper.getBySellerId(order.getSellerId());
			sellerStatistics.setTotalMoney(sellerStatistics.getTotalMoney() + order.getTotalFee());
			sellerStatistics.setNowTotalMoney(sellerStatistics.getNowTotalMoney() + order.getTotalFee());
			fuziongMemberStatisticsMapper.update(sellerStatistics);
			//卖家账户明细记录
			sellRecords = new IncomeExpenditureRecords();
			sellRecords.setMemberId(order.getSellerId());
			sellRecords.setType(FuzionConstants.TYPE_TWO);
			sellRecords.setMoney(order.getTotalFee());
			if(order.getProductId().equals(ProductConstant.EnergyBeanProduct.BEAN_PRODUCT_ID)){
				sellRecords.setObjType(FuzionConstants.IncomeExpenditure.BEAN_SHOPPING);
			} else {
				sellRecords.setObjType(FuzionConstants.IncomeExpenditure.SHOPPING_MONEY);
			}
			sellRecords.setObjId(String.valueOf(order.getId()));
			incomeExpenditureRecordsService.insert(sellRecords);
			//修改订单状态
			order.setStatus(ProductConstant.OrderStatic.ORDER_STATUS_PAY);
			order.setPayMethod(ProductConstant.OrderStatic.PAY_WX);
			order.setPayTime(new Date());
			orderService.update(order);
			if(order.getProductId().equals(ProductConstant.EnergyBeanProduct.BEAN_PRODUCT_ID)){//如果购买的是能量豆,能量豆购买数量加一
				//公排逻辑
				buyThanPublicRow(member.getId());
			}
			memberService.update(member);



			logger.info("****************order and public row success*************");
			return CommonConstants.SUCCESS;
		} catch (Exception e) {
			//mongo手动回滚
			if(records != null && records.getId() > 0){
				incomeExpenditureRecordsService.delete(records.getId());
			}
			if(sellRecords != null && sellRecords.getId() > 0){
				incomeExpenditureRecordsService.delete(sellRecords.getId());
			}
			if(member != null && readed ){
				member.setReaded(false);
				memberService.update(member);
			}
			logger.info("************orderNo exception**********" + orderNo);
			throw new RuntimeException( e + ":::::::::::::::::" + orderNo);
		}
	}
    
    
    /**
     * 微信支付异步回调处理
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional
    public String weixinNotify(HttpServletRequest request, String orderNo) throws Exception{
		IncomeExpenditureRecords records = null;//会员交易记录
        IncomeExpenditureRecords sellRecords = null;//店铺交易记录
        FuzionMember member = null;
		OrderDto order = null;//缓存order
		Order rOrder = null;//数据库order
        boolean readed = true;
        try {
//            AlipayWapResult wapResult = WXPayService.notifyResult(request, "1");
			KQResult result = KQService.verify(request);
//            String orderNo = result.getOutTradeNo();
            order = orderLoader.get(orderNo);
            logger.info("**********order**********"+JSON.toJSONString(order));
            if(order == null || order.isLock() || !order.getStatus().equals(ProductConstant.OrderStatic.ORDER_STATUS_CREATE)){
                logger.info("****************order == null*************");
                return QK_NOTIFY_FAIL;
            }
			order.setLock(true);
			orderLoader.clearCache(orderNo);
			redisCacheClient.set(orderNo, order, 86400);
            member = memberService.getById(order.getMemberId());
            if(member.getReaded()){
                readed = false;
            }
            member.setReaded(true);
            WeixinConfig weixinConfig = weixinConfigService.getById(Long.valueOf(member.getWeixinId()));
//            wapResult = WXPayService.checkIsSuccess(wapResult, weixinConfig.getMcKkey());
			logger.info("****************wapResult*************" + result.toString());
            if (!result.getTradeStatus().equals(CommonConstants.SUCCESS.toUpperCase())) {//签名校验失败
                logger.info("****************sign error*************");
                return QK_NOTIFY_FAIL;
            }
            /*if(wapResult.getPrice().compareTo(new BigDecimal(order.getTotalFee())) != 0){//支付金额不正确
                logger.info("****************price error*************");
                return CommonConstants.FAIL;
            }*/
            //修改订单状态并生成支付记录
            //   能量豆支付的处理
            FuziongMemberStatistics statistics = fuziongMemberStatisticsMapper.getByMemberId(member.getId());
			rOrder = orderService.getById(order.getOrderId());
            if(rOrder.getProductId().equals(ProductConstant.EnergyBeanProduct.BEAN_PRODUCT_ID)){//如果购买的是能量豆,能量豆购买数量加一
				FuziongMemberStatistics memberTemp = new FuziongMemberStatistics();
				memberTemp.setId(statistics.getId());
				memberTemp.setMemberId(statistics.getMemberId());
				memberTemp.setEnergyBean(1);
				memberTemp.setNowEnergyBean(1);
				logger.info("****************能量豆数量加一*************");
				//fuziongMemberStatisticsMapper.update(statistics);//增加能量豆数量
				fuziongMemberStatisticsMapper.updateStatistics(memberTemp);//增加能量豆数量
				redisCacheClient.incr(OrderService.FUZION_MEMBER_BUY_BEAN_COUNT + member.getId());//缓存购买次数
            }
            
            //购买商品 处理推荐人收益
            orderService.recIncome(member, rOrder.getProductId());
            //生成收支明细表
            records = new IncomeExpenditureRecords();
            records.setMemberId(member.getId());
            records.setType(FuzionConstants.TYPE_ONE);
            records.setMoney(0 - rOrder.getTotalFee());
            if(rOrder.getProductId().equals(ProductConstant.EnergyBeanProduct.BEAN_PRODUCT_ID)){
                records.setObjType(FuzionConstants.IncomeExpenditure.BEAN_SHOPPING);
            } else {
                records.setObjType(FuzionConstants.IncomeExpenditure.SHOPPING_MONEY);
            }
            records.setObjId(String.valueOf(rOrder.getId()));
            incomeExpenditureRecordsService.insert(records);
            // 卖家账户余额变动
            FuziongMemberStatistics sellerStatistics = fuziongMemberStatisticsMapper.getBySellerId(rOrder.getSellerId());
            sellerStatistics.setTotalMoney(rOrder.getTotalFee());
            sellerStatistics.setNowTotalMoney(rOrder.getTotalFee());
            fuziongMemberStatisticsMapper.updateStatistics(sellerStatistics);
            //卖家账户明细记录
            sellRecords = new IncomeExpenditureRecords();
            sellRecords.setMemberId(rOrder.getSellerId());
            sellRecords.setType(FuzionConstants.TYPE_TWO);
            sellRecords.setMoney(rOrder.getTotalFee());
            if(rOrder.getProductId().equals(ProductConstant.EnergyBeanProduct.BEAN_PRODUCT_ID)){
                sellRecords.setObjType(FuzionConstants.IncomeExpenditure.BEAN_SHOPPING);
            } else {
                sellRecords.setObjType(FuzionConstants.IncomeExpenditure.SHOPPING_MONEY);
            }
            sellRecords.setObjId(String.valueOf(rOrder.getId()));
            incomeExpenditureRecordsService.insert(sellRecords);
            //修改订单状态
			rOrder.setStatus(ProductConstant.OrderStatic.ORDER_STATUS_PAY);
			rOrder.setPayMethod(ProductConstant.OrderStatic.PAY_WX);
			rOrder.setPayTime(new Date());
            orderService.update(rOrder);

			FuziongMemberStatistics recfms = fuziongMemberStatisticsService.getByMember(member.getRecId());
            if(rOrder.getProductId().equals(ProductConstant.EnergyBeanProduct.BEAN_PRODUCT_ID)){//如果购买的是能量豆,能量豆购买数量加一

				if(recfms != null){
					//设置当前购买人的推荐人今日为勤人标记
					FuziongMemberStatistics recMm = new FuziongMemberStatistics();
					recMm.setId(recfms.getId());
					recMm.setTodayIsBuy(1);
					fuziongMemberStatisticsService.updateStatistics(recMm);
				}

                //公排逻辑
                buyThanPublicRow(member.getId());
            }
            memberService.update(member);
            
            //计算会员的等级
            String scoreName = null;
            ScoreLevel score1 = scoreLevelService.getById(1L);//会员等级青铜
			ScoreLevel score2 = scoreLevelService.getById(2L);//会员等级白金
			ScoreLevel score3 = scoreLevelService.getById(3L);//会员等级王者
			ScoreLevel score4 = scoreLevelService.getById(4L);//会员等级战神
			ScoreLevel score5 = scoreLevelService.getById(5L);//会员等级天罡
			ScoreLevel score6 = scoreLevelService.getById(6L);//会员等级教父
			
            //可能公排的时候  有能量豆产生  所以这里需要再去数据库里取一次
            FuziongMemberStatistics endstatistics = fuziongMemberStatisticsMapper.getByMemberId(member.getId());
			int beanNum = endstatistics.getEnergyBean();//会员当前的能量豆数量
			
			if(score1.getStartScore() < beanNum && beanNum <= score1.getEndScore()){//能量豆 0<n<=3 青铜
				if(statistics.getScoreId() == 0L){
					statistics.setScoreId(1L);//设置会员等级
					scoreName = score1.getLevelName();
				}
			}else if(score2.getStartScore()<beanNum&&beanNum<=score2.getEndScore()){//3<n<=9  白金
				if(statistics.getScoreId() < 2L){//
					statistics.setScoreId(2L);//设置会员等级
					scoreName = score2.getLevelName();
				}
			}else if(score3.getStartScore()<beanNum && beanNum <= score3.getEndScore()){// 9<n<=60 王者
				if(statistics.getScoreId() < 3L){//
					statistics.setScoreId(3L);//设置会员等级
					scoreName = score3.getLevelName();
				}
			}else if(score4.getStartScore()<beanNum && beanNum <= score4.getEndScore()){// 9<n<=60 战神
				if(statistics.getScoreId() < 4L){//
					statistics.setScoreId(4L);//设置会员等级
					scoreName = score4.getLevelName();
				}
			}else if(score5.getStartScore()<beanNum && beanNum <= score5.getEndScore()){// 9<n<=60 天罡
				if(statistics.getScoreId() < 5L){//
					statistics.setScoreId(5L);//设置会员等级
					scoreName = score5.getLevelName();
				}
			}else if(score6.getStartScore()<beanNum && beanNum <= score6.getEndScore()){// 9<n<=60 教父
				if(statistics.getScoreId() < 6L){//
					statistics.setScoreId(6L);//设置会员等级
					scoreName = score6.getLevelName();
				}
			}
			
			//修改会员等级  并告知会员等级提升了
			if(StringUtils.isNotBlank(scoreName)){
				
				FuziongMemberStatistics statistics2 = new FuziongMemberStatistics();
				
				statistics2.setId(statistics.getId());
				statistics2.setMemberId(statistics.getMemberId());
				statistics2.setScoreId(statistics.getScoreId());
				fuziongMemberStatisticsService.updateByMemberId(statistics2);
				
				FuzionMemberRedisDto redis_fuzion_member = memberService.getFuzionMemberRedisDto(member.getId());
				WeixinSendInfo wsss = weixinSendInfoService.getByKey("score_level_to_up");
				String messagess = wsss.getValue().replace("{scoreName}", scoreName);
				WeixinSendUtils.sendMessage(redis_fuzion_member.getAppId(), redis_fuzion_member.getAppSecret(),
						redis_fuzion_member.getOpenId(), messagess);
				/*WeixinSendInfoThread.sendMessage(redis_fuzion_member.getAppId(), redis_fuzion_member.getAppSecret(),
						redis_fuzion_member.getOpenId(), messagess);*/
			}
			
			//因为会员买了能量豆  就是有效的推荐的人  所以要计算当前会员的推荐人的会员等级
			//根据推荐的人数  设置推荐人会员等级
			//FuziongMemberStatistics recfms = fuziongMemberStatisticsService.getByMember(member.getRecId());
			if(recfms != null){
				String recscoreName = null;
				Long recCount = memberService.countMemberByRecId2(member.getRecId());//已经推荐的会员数量
				
				if(recCount > score1.getStartScore() && recCount < score1.getEndScore()){//推荐人  0<n<3 青铜
					if(recfms.getScoreId() < 1L){
						recfms.setScoreId(1L);
						recscoreName = score1.getLevelName();
					}
				}else if(score2.getStartScore() <= recCount && recCount < score2.getEndScore()){  //3<=n<9 白金
					if(recfms.getScoreId()<2L){
						recfms.setScoreId(2L);
						recscoreName = score2.getLevelName();
					}
				}else if(recCount >= score3.getStartScore() && recCount < score3.getEndScore()){//  9<=n<60 王者
					if(recfms.getScoreId()<3L){
						recfms.setScoreId(3L);
						recscoreName = score3.getLevelName();
					}
				}else if(recCount >= score4.getStartScore() && recCount < score4.getEndScore()){//  60<=n<600 战神
					if(recfms.getScoreId()<4L){
						recfms.setScoreId(4L);
						recscoreName = score4.getLevelName();
					}
				}else if(recCount >= score5.getStartScore() && recCount < score5.getEndScore()){//  600<=n<2000 天罡
					if(recfms.getScoreId()<5L){
						recfms.setScoreId(5L);
						recscoreName = score5.getLevelName();
					}
				}else if(recCount >= score6.getStartScore() && recCount < score6.getEndScore()){//  2000<=n<999999 教父
					if(recfms.getScoreId()<6L){
						recfms.setScoreId(6L);
						recscoreName = score6.getLevelName();
					}
				}
				
				//修改推荐人会员等级 并告知会员等级提升了
				if(StringUtils.isNotBlank(recscoreName)){
					fuziongMemberStatisticsService.updateByMemberId(recfms);
					
					FuzionMemberRedisDto redis_fuzion_member = memberService.getFuzionMemberRedisDto(member.getRecId());
					WeixinSendInfo wsss = weixinSendInfoService.getByKey("score_level_to_up");
					String messagess = wsss.getValue().replace("{scoreName}", recscoreName);
					WeixinSendUtils.sendMessage(redis_fuzion_member.getAppId(), redis_fuzion_member.getAppSecret(),
							redis_fuzion_member.getOpenId(), messagess);
				}
				
			}
			orderLoader.clearCache(orderNo);
            logger.info("****************success*************");
            return QK_NOTIFY_SUCCESS.replace("{url}", resourceHolder.getStringValue("webRoot") + "/weixin/order/paySuccess?orderId=" + order.getOrderId());
        } catch (Exception e) {
			if(order != null){
				order.setLock(false);
				order.setStatus(ProductConstant.OrderStatic.ORDER_STATUS_CREATE);
				orderLoader.clearCache(order.getOrderNo());
				redisCacheClient.set(order.getOrderNo(), order, 86400);
			}
            //mongo手动回滚
            if(records != null && records.getId() > 0){
                incomeExpenditureRecordsService.delete(records.getId());
            }
            if(sellRecords != null && sellRecords.getId() > 0){
                incomeExpenditureRecordsService.delete(sellRecords.getId());
            }
            if(member != null && readed ){
                member.setReaded(false);
                memberService.update(member);
            }
			if(rOrder != null){
				rOrder.setStatus(ProductConstant.OrderStatic.ORDER_STATUS_CREATE);
				rOrder.setPayMethod(null);
				rOrder.setPayTime(null);
				orderService.update(rOrder);
			}
            throw new RuntimeException(e);
        }
    }
    
    
    /**
	 * 公排逻辑
	 * @param memberId
	 */
//    @Transactional
	public void buyThanPublicRow(Long memberId){
		
		try{
			Long index = redisCacheClient.get(FUZION_PUBLIC_ROW_KEY, Long.class);
			if(index == null){//新的开始  或者redis缓存服务器重启
				index = publicRowService.getMaxId();
				if(index == null){
					index = 0L;
				}
				redisCacheClient.set(FUZION_PUBLIC_ROW_KEY, index, 0);//将数据库中 最后一条数据的ID值  放入缓存中
			}
			Long pushId = indexId(index + 1L);//计算弹出值
			String openTime="";

			PublicRow pr = new PublicRow();
			pr.setMemberId(memberId);
			pr.setPushId(pushId);
			pr.setCreateTime(new Date());
			publicRowService.insert(pr);

			redisCacheClient.set(FUZION_PUBLIC_ROW_KEY, pr.getId(), 0);//重新设定缓存中pushId的值
			redisCacheClient.set(FUZION_PUBLIC_ROW_DTO+pr.getId(), pr, 0);//将公排的坑位信息放入redis中

			//FUZION_PUBLIC_ROW_PUSHID_NUM
			Long pushIdNum = redisCacheClient.get(FUZION_PUBLIC_ROW_PUSHID_NUM + pushId, Long.class);
			if(pushIdNum == null){
				Map<String, Object> resut = publicRowService.countNowInfo();
				pushIdNum = (Long)resut.get("num");
				redisCacheClient.set(FUZION_PUBLIC_ROW_PUSHID_NUM + pushId, pushIdNum, 0);
			}else{
				pushIdNum = redisCacheClient.incr(FUZION_PUBLIC_ROW_PUSHID_NUM + pushId);
			}

			/*Map<String, Object> resut = publicRowService.countNowInfo();
			Long renum = (Long)resut.get("num");*/
			//Long repushId = (Long)resut.get("pushId");
			if(pushIdNum >= 3){//如果满足抽奖条件  就从抽奖池中删除  表示已经抽过奖
				PublicRow fms = redisCacheClient.get(FUZION_PUBLIC_ROW_DTO+pushId, PublicRow.class);
				if(fms == null){
					fms = publicRowService.getById(pushId);
				}
				if(fms.getCreateTime() == null){
					fms = publicRowService.getById(pushId);
				}
				//PublicRow fms = publicRowService.getById(pushId);
				/*PublicRow delefms = redisCacheClient.get(FUZION_PUBLIC_ROW_DTO+repushId, PublicRow.class);
				if(delefms == null){
					delefms = publicRowService.getById(repushId);
				}*/
				//PublicRow delefms = publicRowService.getById(repushId);
				publicRowService.delete(pushId);

				redisCacheClient.del(FUZION_PUBLIC_ROW_DTO+pushId);//将开过奖的坑位信息从缓存中删除
				redisCacheClient.del(FUZION_PUBLIC_ROW_PUSHID_NUM + pushId);
				
				PublicRowRecord prr = new PublicRowRecord();
				prr.setMemberId(fms.getMemberId());
				prr.setPushId(fms.getId());//这里的弹出ID  就是这条memberid的ID值
				publicRowRecordService.insert(prr);//插入一条记录
				
				//重新计算已玩局数 静态收益(开奖部分)
				if(fms.getCreateTime() == null){
					reStatistics(fms.getMemberId(), "");
				}else{
					reStatistics(fms.getMemberId(), TimeUtils.format(fms.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
				}
				//reStatistics(fms.getMemberId(), TimeUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
			}
			
			
		}catch(Exception e){
			e.printStackTrace();
			logger.error("PublicRowService.buyThanPublicRow error", e);
		}
	}
	
	/**
	 * 重新计算已玩局数 静态收益(开奖部分)
	 * @param memberId : 弹出人的ID
	 */
//	@Transactional
	private void reStatistics(Long memberId, String openTime){
		try{
			logger.info("==============reStatistics memberId================" + memberId);
			SysDictionary bas = sysDictionaryService.getByField("key", "bean_award_scale");
			int bean_award_scale = 0;
			if(bas != null){
				bean_award_scale = bas.getValue() * 100;//扩大100倍  元转分
			}
			
			FuziongMemberStatistics fms = fuziongMemberStatisticsService.getByMember(memberId);
			FuziongMemberStatistics fmsMm = new FuziongMemberStatistics();
			fmsMm.setId(fms.getId());
			fmsMm.setMemberId(fms.getMemberId());
			fmsMm.setPlayNum(fms.getPlayNum() + 1);//已玩局数+1
			fmsMm.setNowEnergyBean(1);//现在持有的能量豆数量+1
			fmsMm.setEnergyBean(1);//历史拥有的能量豆数量+1

			fmsMm.setTotalMoney(bean_award_scale);//因为开奖  +202块钱
			fmsMm.setStaticIncome(bean_award_scale);//开奖 静态收益+202块钱
			fmsMm.setNowTotalMoney(bean_award_scale);//总积分要加上202
			//根据能量豆计算会员等级
			/*String scoreName = null;
			ScoreLevel scoreLevel = scoreLevelService.getByScore(fms.getEnergyBean() - 1);
			if(scoreLevel != null && fms.getScoreId() < scoreLevel.getId()){
				scoreName = scoreLevel.getLevelName();
				fms.setScoreId(scoreLevel.getId());//设置会员等级
            }else if(scoreLevel == null && fms.getEnergyBean() == 1){//会员只购买了一个能量豆
            	if(fms.getScoreId() == 0){//还没有会员等级时  设置为青铜   如果有其他会员等级  不作处理
            		scoreName = "青铜";
            		fms.setScoreId(1L);//设置会员等级
            	}
            }*/
			String scoreName = null;
			int beanNum = fms.getEnergyBean();
            if(0 < beanNum && beanNum <= 3 && fms.getScoreId() == 0){//能量豆 0<n<=3
				fmsMm.setScoreId(1L);//设置会员等级
        		scoreName = "青铜";
            }else if(4<=beanNum&&beanNum<=9){//4<n<9   
            	if(fms.getScoreId() < 2){//
					fmsMm.setScoreId(2L);//设置会员等级
            		scoreName = "白金";
            	}
            }else if(10<=beanNum){//n>10
            	if(fms.getScoreId() < 3){//
					fmsMm.setScoreId(3L);//设置会员等级
            		scoreName = "王者";
            	}
            }
			
			logger.info("==============reStatistics fuziongMemberStatisticsMapper.update================" + JSON.toJSONString(fms));
			fuziongMemberStatisticsMapper.updateStatistics(fmsMm);
			logger.info("开奖后，重新计算已玩局数、静态收益成功：FuziongMemberStatistics="+JSON.toJSONString(fms));

			//记录开奖人收益
			IncomeExpenditureRecords memberRecords = new IncomeExpenditureRecords();
			memberRecords.setMemberId(memberId);
			memberRecords.setMoney(bean_award_scale);
			memberRecords.setObjType(FuzionConstants.IncomeExpenditure.OPEN_GIVE_MONEY);
			memberRecords.setObjId(memberId + "");
			incomeExpenditureRecordsService.insert(memberRecords);

			
			//开奖成功后，重新计算店铺的收益  也就是把开奖产生的分红也计算到店铺收益里
			SysDictionary sellerScaleDictionary = sysDictionaryService.getByField("key", ProductConstant.EnergyBeanProduct.BEAN_PRICE);
			FuziongMemberStatistics sellerMember = fuziongMemberStatisticsMapper.getBySellerId(fms.getSellerId());
			sellerMember.setTotalMoney(sellerScaleDictionary.getValue()*100);
			sellerMember.setNowTotalMoney(sellerScaleDictionary.getValue()*100);
			//fuziongMemberStatisticsMapper.update(sellerMember); updateStatistics
			fuziongMemberStatisticsMapper.updateStatistics(sellerMember);

			
			//给开奖人的上一级  分配提成
			SysDictionary scaleDictionary = sysDictionaryService.getByField("key", ProductConstant.EnergyBeanProduct.BEAN_SCALE);
			Integer income = Integer.valueOf(scaleDictionary.getValue()) * 100;
			FuzionMemberRedisDto fmrd = memberService.getFuzionMemberRedisDto(memberId);
			FuziongMemberStatistics recMember = fuziongMemberStatisticsMapper.getByMemberId(fmrd.getRecId());
			FuzionMemberRedisDto redis_fuzion_member = memberService.getFuzionMemberRedisDto(memberId);
			
			if(recMember != null){//推荐人不是店铺
				FuziongMemberStatistics recMm = new FuziongMemberStatistics();
				recMm.setId(recMember.getId());
				recMm.setMemberId(recMember.getMemberId());
				recMm.setNowTotalMoney(income);
				recMm.setDynamicIncome(income);
				recMm.setTotalMoney(income);
				fuziongMemberStatisticsMapper.updateStatistics(recMm);

				//记录开奖人收益
				IncomeExpenditureRecords RecMemberRecords = new IncomeExpenditureRecords();
				RecMemberRecords.setMemberId(memberId);
				RecMemberRecords.setMoney(bean_award_scale);
				RecMemberRecords.setObjType(FuzionConstants.IncomeExpenditure.TEAM_OPEN_GIVE_MONEY);
				RecMemberRecords.setObjId(memberId + "");
				incomeExpenditureRecordsService.insert(RecMemberRecords);
				
				//开奖成功后 推送给推荐人的收益
				//FuzionMember recM = memberService.getById(fmrd.getRecId());
				WeixinSendInfo sendInfo = weixinSendInfoService.getByKey("my_team_opean_scale");
				if(StringUtils.isNotEmpty(redis_fuzion_member.getRecOpenId())){
					Double income1 = new BigDecimal(income).divide(new BigDecimal(100)).doubleValue();
					WeixinSendUtils.sendMessage(redis_fuzion_member.getAppId(), redis_fuzion_member.getAppSecret(), redis_fuzion_member.getRecOpenId(),
		                    sendInfo.getValue().replace("{memberName}",redis_fuzion_member.getMemName()).replace("{money}", income1+""));
				}
			}
			
			//推送给开奖者的收益 您的{openTime}排位已开奖，恭喜您获得{money}积分和一颗能量豆
			WeixinSendInfo ws = weixinSendInfoService.getByKey("the_lottery_success");
			String message = ws.getValue().replace("{money}", String.valueOf(bean_award_scale/100)).replace("{openTime}", openTime);
			WeixinSendUtils.sendMessage(redis_fuzion_member.getAppId(), redis_fuzion_member.getAppSecret(),
					redis_fuzion_member.getOpenId(), message);

			//告知会员等级提升了
			if(StringUtils.isNotBlank(scoreName)){
				WeixinSendInfo wsss = weixinSendInfoService.getByKey("score_level_to_up");
				String messagess = wsss.getValue().replace("{scoreName}", scoreName);
				WeixinSendUtils.sendMessage(redis_fuzion_member.getAppId(), redis_fuzion_member.getAppSecret(),
						redis_fuzion_member.getOpenId(), messagess);
			}
			
			//开奖后  当前开奖人复投
			buyThanPublicRow(memberId);
		}catch(Exception e){
			e.printStackTrace();
			logger.error("PublicRowService.reStatistics error", e);
		}
		
		
	}
	
	/**
	 * 通过id 计算弹出的ID
	 * @param id
	 * @return
	 */
	private Long indexId(Long id){
		return Math.round(Math.ceil((id+1l)/3l));
	}
}
